package cn.legym.garp.gateway.traffic.dynamic.context;

import com.google.common.collect.Lists;
import com.google.common.collect.Queues;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Queue;

/**
 * create by pipisun on 2021/9/16
 * copyright © 2017-2021 Legym Technology Co.,Ltd. All rights reserve
 * d.
 * file description:
 * last update by {} on {}
 * update description:
 */
@Slf4j
public class PropertyUpdateEventQueue {

    private static final Integer CAPACITY = 9999;
    private static final Queue<UpdateEvent> queue = Queues.newConcurrentLinkedQueue();

    public static void push(UpdateEvent event) {
        if (queue.size() >= CAPACITY) {
            log.warn("UpdatePropertyEventQueue is full!");
            return;
        }
        queue.add(event);
    }

    public static void execute() {
        if (queue.isEmpty()) {
            return;
        }
        List<UpdateEvent> events = Lists.newArrayList();
        UpdateEvent event;
        while ((event = queue.poll()) != null) {
            events.add(event);
        }
        events.forEach(UpdateEvent::action);
    }

    @FunctionalInterface
    public interface UpdateEvent {
        void action();
    }

}
